package com.hjx.filter;


import com.hjx.mapper.UserMapper;
import com.hjx.pojo.Permission;
import com.hjx.pojo.User;
import com.hjx.utils.MybatisUtil;
import jdk.nashorn.internal.runtime.regexp.joni.encoding.CharacterType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MyFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        HttpServletResponse sr = (HttpServletResponse) servletResponse;

        String username = servletRequest.getParameter("username");
        System.out.println("username = " + username);
        UserMapper mapper = MybatisUtil.getMapper(UserMapper.class, false);
        User infoByUname = mapper.findInfoByUname(username);
        if (infoByUname==null){
            sr.sendRedirect("login.jsp");
        }else {
            System.out.println("infoByUname = " + infoByUname);
            ArrayList<Integer> list = new ArrayList<>();
            for (Permission permission : infoByUname.getPermission()) {
                list.add(permission.getPid());
            }
            ArrayList<Integer> l = new ArrayList<>();
            l.add(2);
            l.add(3);
            l.add(4);
            boolean b = false;
            for (Integer integer : list) {
                if (l.contains(integer)) {
                    b = true;
                }
            }
            if (b) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                sr.sendRedirect("noauthen.jsp");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
